package com.lagou.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @Author wsl
 * @Date 2021/8/22 21:23
 * @Project_Name mysql
 */
public class C3P0Utils {

    //1.创建连接池对象，C3P0对DataSource接口的实现类
    //public static ComboPooledDataSource dataSource = new ComboPooledDataSource();

    //使用指定的配置
    public static ComboPooledDataSource dataSource = new ComboPooledDataSource("mysql");

    //2.获取连接的方法
    public static Connection getConnection() throws SQLException {
        //从连接池中获取连接
        return dataSource.getConnection();
    }

    //3.释放资源
    public static void close(Connection con, Statement statement){
        if (null != con && null != statement){
            try {
                statement.close();
                //.归还连接
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    //4.释放资源，用于查询
    public static void close(Connection con, Statement statement, ResultSet resultSet){
        if (null != con && null != statement && null != resultSet){
            try {
                resultSet.close();
                statement.close();
                //.归还连接
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
